package com.gitee.liuzhi.framework.starter.response.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author: LiuZhi
 * @date: 2022/5/5 19:54
 * @description: request and response log-print
 */
@Slf4j
public class ControllerLogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (log.isDebugEnabled()) {
            log.info(
                    "\r\n==========================request begin==============================================\r\n"
                            + "Request URI       : {}\r\n" + "Request Method    : {}\r\n"
                            + "Request Parameter : {}\r\n"
                            + "==========================request end================================================",
                    request.getRequestURI(), request.getMethod(),
                    Objects.nonNull(request.getContentType())
                            && request.getContentType().startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)
                            ? "File Stream" : JSON.toJSONString(request.getParameterMap())
            );
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 业务执行成功
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 业务执行成功与否都会执行
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
